<template>
  <div class="login-page">
    <van-nav-bar left-arrow />
    <h3>短信登录</h3>
    <van-form>
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        v-model="username"
        name="pattern"
        placeholder="请输入手机号"
        :rules="[
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入手机号' },
        ]"
      />

      <van-field
        v-model="password"
        name="pattern"
        placeholder="请输入验证码"
        :rules="[{ pattern: /^\d{6}$/, message: '请输入正确的验证码' }]"
      >
        <template #button>
          <van-button size="small" type="primary" @click="timeOut">
            <!-- <span v-if="time === 0">发送验证码</span>
   <span v-else>{{ `${time}秒后发送` }}</span> -->
            {{ time === 0 ? "发送验证码" : `${time}秒后发送` }}
          </van-button>
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" @click="gogin"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'LoginPage',
  data () {
    return {
      username: '',
      password: '',
      pattern: '',
      time: 0,
      // flag: true,
      timeId: ''
    }
  },
  methods: {
    async timeOut () {
      const res = await axios.get(`http://toutiao.itheima.net/v1_0/sms/codes/${this.username}`)
      console.log(res)
      this.time = 60
      this.timeId = setTimeout(() => {
        this.time--
        if (this.time === 0) {
          clearInterval(this.timeId)
        }
      }, 1000)
    },
    async   gogin () {
      try {
        const res = await axios.post('http://toutiao.itheima.net/v1_0/authorizations', {
          mobile: this.username,
          code: this.password
        })
        console.log(res)
        console.log(res.status)
        if (res.status >= 200 || res.status < 300) {
          localStorage.setItem('token', res.data.data.token)
          localStorage.setItem('refresh_token', res.data.data.refresh_token)
          console.log('登录成功')
          location.href = '@/views/one-level-router/Login#/home'
        }
      } catch (e) {
        console.log(e.request.response)
      }
    }
  }

}
</script>

<style lang="less" scoped>
h3 {
  font-size: 18px;
  font-weight: normal;
  padding: 20px 28px;
}
.van-form {
  padding: 0 10px;
}
</style>
